package Python

import (
	"BackEnd/GrpcProto"
	"fmt"
	"io"
	"log"
	"strings"
	"time"

	"github.com/gin-gonic/gin"
	"golang.org/x/net/context"
	"google.golang.org/grpc"
)

// 连接python图数据库查询服务
func NewGraphDataServer() *server {
	conn, err := grpc.Dial("localhost:50052", grpc.WithInsecure())
	if err != nil {
		log.Fatalln("[Fail]: NewGraphDataServer %v", err)
	}
	return &server{
		pythonGraphDataClient: GrpcProto.NewGo_Py_GraphDataClient(conn),
	}
}

// 连接python问答服务
func NewAnswerServer() *server {
	conn, err := grpc.Dial("localhost:50052", grpc.WithInsecure())
	if err != nil {
		log.Fatalln("[Fail]: NewAnswerServer %v", err)
	}
	return &server{
		pythonAnswerClient: GrpcProto.NewGo_Py_AnswerClient(conn),
	}
}

// 连接python文件解析服务
func NewAnalyzeServer() *server {
	conn, err := grpc.Dial("localhost:50052", grpc.WithInsecure())
	if err != nil {
		log.Fatalln("[Fail]: NewAnalyzeServer %v", err)
	}
	return &server{
		pythonAnalyzeClient: GrpcProto.NewGo_Py_AnalyzeClient(conn),
	}
}

// 调用python图数据库查询服务
func (s *server) Go_Py_GraphData(ctx context.Context, req *GrpcProto.GraphDataRequest) (*GrpcProto.GraphDataResponse, error) {
	log.Printf("[Info:Call]: Go_Py_GraphData %s", req.Question)

	// 创建带超时的上下文
	ctx, cancel := context.WithTimeout(ctx, 1000*time.Second)
	defer cancel()

	// 直接调用Python服务（非流式）
	resp, err := s.pythonGraphDataClient.GetGraphData(ctx, req)
	if err != nil {
		return nil, fmt.Errorf("[Fail]: Go_Py_GraphData %v", err)
	}
	return resp, nil
}

// 调用python问答服务
func (s *server) Go_Py_Answer(ctx context.Context, req *GrpcProto.AnswerRequest) (*GrpcProto.AnswerResponse, error) {
	log.Printf("[Info:Call]: Go_Py_Answer %s", req.Cue)

	// 创建带超时的上下文
	ctx, cancel := context.WithTimeout(ctx, 1000*time.Second)

	// 获取流式响应
	stream, err := s.pythonAnswerClient.GetAnswer(ctx, req)
	if err != nil {
		cancel()
		return nil, fmt.Errorf("[Fail]: Go_Py_Answer %v", err)
	}

	var fullAnswer strings.Builder
	for {
		resp, err := stream.Recv()
		if err == io.EOF {
			break
		}
		if err != nil {
			return nil, fmt.Errorf("[Fail]: Go_Py_Answer %v", err)
		}

		if resp.Done {
			break
		}

		fullAnswer.WriteString(resp.Text + "\n")
		// fmt.Printf("收到流式响应: %s\n", resp.Text)
	}

	return &GrpcProto.AnswerResponse{Text: fullAnswer.String()}, nil
}

// 调用python文件解析服务
func (s *server) Go_Py_Analyze(ctx context.Context, req *GrpcProto.AnalyzeRequest) (*GrpcProto.AnalyzeResponse, error) {
	log.Printf("[Info:Call]: Go_Py_Analyze %v", req.Name)

	// 创建带超时的上下文
	ctx, cancel := context.WithTimeout(ctx, 1000*time.Second)
	defer cancel()

	// 直接调用Python服务（非流式）
	resp, err := s.pythonAnalyzeClient.Analyze(ctx, req)
	if err != nil {
		return nil, fmt.Errorf("[Fail]: Go_Py_Analyze %v", err)
	}
	return resp, nil
}

// GetAnswer 获得并返回针对用户提问的回答
func GetAnswer(c *gin.Context, cue []string) (error, *GrpcProto.AnswerResponse) {
	AnswerServer := NewAnswerServer()
	respAnswer, err := AnswerServer.Go_Py_Answer(c.Request.Context(), &GrpcProto.AnswerRequest{
		Cue: cue,
	})
	if err != nil {
		return err, nil
	}

	return nil, respAnswer
}

// GetGraphData 获得并返回用于生成前端图数据库的查询语句
func GetGraphData(c *gin.Context, question string) (error, *GrpcProto.GraphDataResponse) {
	GraphDataServer := NewGraphDataServer()
	respGraphData, err := GraphDataServer.Go_Py_GraphData(c.Request.Context(), &GrpcProto.GraphDataRequest{
		Question: question,
	})
	if err != nil {
		return err, nil
	}

	return err, respGraphData
}

func AnalyzeFile(c *gin.Context, name string, content []byte) (error, *GrpcProto.AnalyzeResponse) {
	AnalyzeServer := NewAnalyzeServer()
	respAnalyze, err := AnalyzeServer.Go_Py_Analyze(c.Request.Context(), &GrpcProto.AnalyzeRequest{
		Name:    name,
		Content: content,
	})
	if err != nil {
		return err, nil
	}

	return nil, respAnalyze
}
